package com.example.dense_rack_server.utils.DataBackup;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 数据恢复
 */
@Service
public class SqlFileExecutor {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 执行classpath下的SQL文件
     * @param filePath SQL文件路径（如：sql/init_data.sql）
     */
    public void executeSqlFile(String filePath) throws Exception {
        // 读取SQL文件
//        ClassPathResource resource = new ClassPathResource(filePath);
        FileInputStream fis = new FileInputStream(filePath);
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(fis, StandardCharsets.UTF_8))) {

            // 按";"分割SQL语句（处理多行语句）
            StringBuilder sqlBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty() || line.startsWith("--") || line.startsWith("/*")) {  // 跳过空行和注释
                    continue;
                }
                if (line.contains("LOCK TABLES")) {
                    System.out.println("跳过锁表语句：" + line);
//                    line = "BEGIN;";
//                    sqlBuilder.append(line);
                    continue;
                }
                if (line.contains("UNLOCK TABLES")) {
//                    System.out.println("跳过解锁表语句：" + line);
//                    line = "COMMIT;";
                    continue;
                }
                sqlBuilder.append(line);
                if (line.endsWith(";")) {  // 遇到分号则执行
                    jdbcTemplate.execute(sqlBuilder.toString());
                    sqlBuilder.setLength(0);  // 重置
                }
            }
        }
    }
}
